<script>
import DeviceApi from '../../api/device'
import { useUserStore } from '../../stores/user'
import DeviceBookingForm from '../../components/device/DeviceBookingForm.vue'

import DeviceFeedback from '../../components/deviceFeedback/DeviceFeedback.vue'

// 导入日历组件和样式
import { CalendarView, CalendarViewHeader } from "vue-simple-calendar"
import "vue-simple-calendar/dist/vue-simple-calendar.css"
// 可以选择导入默认主题，或者根据需要自定义
import "vue-simple-calendar/dist/css/default.css"

export default {
  components: {
    DeviceBookingForm,
    DeviceFeedback,
    CalendarView, // 添加日历组件
    CalendarViewHeader // 添加日历头部组件
  },
  data() {
    return {
      device: {},
      showConfirmDialog: false,
      usageRecords: [],
      // 日历相关数据
      showDate: new Date(), // 当前日历显示的日期
      calendarItems: [], // 格式化后的预约事件
    }
  },
  computed: {
    isAdmin() {
      const userStore = useUserStore();
      return userStore.isAdmin;
    },
    deviceInfo() {
      let data = {}
      for (const key in this.device) {
        if (Object.hasOwnProperty.call(this.device, key)) {
          if (!this.device[key]) {
            data[key] = '\u3000'
          } else {
            data[key] = this.device[key]
          }
          if (key === 'intro') {
            data[key] = this.device[key].replace(/\n/g, '</p><p>')
            data[key] = `<p>${data[key]}</p>`
          }
        }
      }
      return data
    },
  },
  methods: {
    async getDevice(deviceId) {
      try {
        const api = new DeviceApi()
        let res = await api.find(deviceId)
        this.device = res.data
        console.log('Device data:', this.device)

        // 获取设备预约记录
        const bookingsRes = await api.getBookings(deviceId)
        console.log('Raw bookings response:', bookingsRes)
        
        if (bookingsRes.code === 200 && Array.isArray(bookingsRes.data)) {
          // 过滤掉已取消和已完成的预约
          const validBookings = bookingsRes.data.filter(booking => 
            booking && 
            booking.status !== 'cancelled' && 
            booking.status !== 'completed'
          );
          
          this.calendarItems = validBookings.map(booking => {
            if (!booking) return null;
            try {
              return {
                id: String(booking.id || ''),
                startDate: new Date(booking.startTime || Date.now()),
                endDate: new Date(booking.endTime || Date.now()),
                title: `预约用户: ${booking.username || '未知'}` + (booking.status === 'pending' ? ' (待审核)' : ''),
                classes: [this.getStatusClass(booking.status || 'pending')],
                purpose: booking.purpose || '未填写使用目的'
              }
            } catch (err) {
              console.error('Error processing booking:', err, booking);
              return null;
            }
          }).filter(item => item !== null);
          
          console.log('Final calendar items:', this.calendarItems)
        } else {
          console.error('Invalid bookings response:', bookingsRes)
          this.$myMessageBox(bookingsRes.msg || '获取设备预约记录失败')
        }

      } catch (err) {
        console.error('Error in getDevice:', err)
        this.$myMessageBox('应用服务器访问错误！')
      }
    },
    async delDevice(deviceId) {
      try {
        const api = new DeviceApi()
        let res = await api.delete(deviceId)
        if (res.code === 204) {
          this.$myMessageBox(res.msg)
          this.$router.replace({ name: 'device-list' })
        }
      } catch (err) {
        console.error(err)
        this.$myMessageBox('应用服务器访问错误！')
      }
    },
    goBack() {
      this.$router.go(-1)
    },
    showBookingForm() {
      this.showConfirmDialog = true
    },
    confirmBooking() {
      this.showConfirmDialog = false
      this.$refs.bookingForm.show()
    },
    handleBookingSuccess() {
      // 预约成功后，跳转到用户的预约记录页面
      this.$router.push('/device/bookings')
    },
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return '';
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    // 获取预约状态对应的CSS类名
    getStatusClass(status) {
      const statusMap = {
        pending: 'status-pending',
        approved: 'status-approved',
        rejected: 'status-rejected',
        completed: 'status-completed',
        cancelled: 'status-cancelled'
      }
      return statusMap[status] || 'status-pending'
    },
    // 设置日历显示日期
    setShowDate(d) {
      this.showDate = d;
    },
  },
  mounted() {
    let deviceId = this.$route.params.id
    this.getDevice(deviceId).then(() => {
        // 在设备数据加载完成后加载使用记录
        // this.loadUsageRecords();
    })
  },
}
</script>

<template>
  <div class="device-detail w80">
    <div class="header">
      <h2>{{ deviceInfo.title }}</h2>
      <div class="header-buttons">
        <a v-if="!isAdmin" class="button primary" href="javascript:void(0);" @click="showBookingForm">立即预约</a>
        <!-- 只有管理员可以看到编辑和删除按钮 -->
        <template v-if="isAdmin">
          <router-link class="button" :to="'/device/edit/' + deviceInfo.id">编辑</router-link>
          <a class="button" href="javascript:void(0);" @click="delDevice(deviceInfo.id)">删除</a>
        </template>
        <a class="button" href="javascript:void(0);" @click="goBack">返回</a>
      </div>
    </div>

    <div class="section">
      <h3>仪器信息</h3>
      <div class="instrument-info-block">
        <img :src="deviceInfo.imageurl" :alt="deviceInfo.title" />
        <div class="info-list">
          <dl>
            <dt>仪器名称：</dt>
            <dd>{{ deviceInfo.title }}</dd>
          </dl>
          <dl>
            <dt>英文名称：</dt>
            <dd>{{ deviceInfo.englishName || '\u3000' }}</dd>
          </dl>
          <dl>
            <dt>所属分类：</dt>
            <dd>{{ deviceInfo.category || '\u3000' }}</dd>
          </dl>
          <dl>
            <dt>品牌：</dt>
            <dd>{{ deviceInfo.brand }}</dd>
          </dl>
          <dl>
            <dt>型号：</dt>
            <dd>{{ deviceInfo.spcialtype }}</dd>
          </dl>
          <dl>
            <dt>产地：</dt>
            <dd>{{ deviceInfo.origin || '\u3000' }}</dd>
          </dl>
          <dl>
            <dt>启用日期：</dt>
            <dd>{{ deviceInfo.status }}</dd>
          </dl>
          <dl>
            <dt>学科领域：</dt>
            <dd>{{ deviceInfo.description }}</dd>
          </dl>
          <dl>
            <dt>技术指标：</dt>
            <dd>{{ deviceInfo.technicalSpecs }}</dd>
          </dl>
          <dl>
            <dt>主要功能：</dt>
            <dd>{{ deviceInfo.mainFunctions }}</dd>
          </dl>
        </div>
      </div>
    </div>

    <div class="section">
      <h3>服务信息</h3>
      <div class="info-list">
        <dl>
          <dt>服务内容：</dt>
          <dd>{{ deviceInfo.serviceContent }}</dd>
        </dl>
        <dl>
          <dt>收费标准：</dt>
          <dd>{{ deviceInfo.price }}</dd>
        </dl>
        <dl>
          <dt>用户须知：</dt>
          <dd>{{ deviceInfo.openSharingRules }}</dd>
        </dl>
      </div>
    </div>

    <div class="section">
      <h3>联系方式</h3>
      <div class="info-list">
        <dl>
          <dt>所在单位：</dt>
          <dd>{{ deviceInfo.danwei }}</dd>
        </dl>
        <dl>
          <dt>联系人：</dt>
          <dd>{{ deviceInfo.contact }}</dd>
        </dl>
        <dl>
          <dt>联系电话：</dt>
          <dd>{{ deviceInfo.phone }}</dd>
        </dl>
        <dl>
          <dt>电子邮箱：</dt>
          <dd>{{ deviceInfo.email }}</dd>
        </dl>
        <dl>
          <dt>仪器地址：</dt>
          <dd>{{ deviceInfo.location || '\u3000' }}</dd>
        </dl>
      </div>
    </div>

    <div class="section">
      <h3>使用指南</h3>
      <div class="usage-guide">
        <div class="guide-content">
          <h4>使用须知</h4>
          <div class="notice-list">
            <p>1. 请仔细阅读设备使用说明，确保正确操作设备。</p>
            <p>2. 使用过程中如遇问题，请及时联系管理员。</p>
            <p>3. 请爱护设备，保持设备清洁。</p>
            <p>4. 使用完毕后请及时归还，确保设备状态完好。</p>
            <p>5. 如有损坏，请及时报告并承担相应责任。</p>
          </div>
          <h4>使用说明</h4>
          <div class="manual-content" v-html="deviceInfo.technicalSpecs"></div>
        </div>
      </div>
    </div>

    <!-- <div class="section">
      <h3>使用记录</h3>
      <div class="usage-records">
        <div v-if="usageRecords.length === 0" class="no-records">
          暂无使用记录
        </div>
        <div v-else class="record-list">
          <div v-for="record in usageRecords" :key="record.id" class="record-item">
            <div class="record-header">
              <span class="user-name">{{ record.username }}</span>
              <span class="record-time">{{ formatDate(record.created_time) }}</span>
            </div>
            <div class="record-content">{{ record.usage_note }}</div>
          </div>
        </div>
      </div>
    </div> -->

    <!-- 预约表单组件 -->
    <device-booking-form
      ref="bookingForm"
      :device-id="deviceInfo.id"
      :device-title="deviceInfo.title"
      @booking-success="handleBookingSuccess"
    />

    <!-- 预约确认对话框 -->
    <div class="booking-confirm-dialog" v-if="showConfirmDialog">
      <div class="dialog-content">
        <h3>预约确认</h3>
        <div class="confirm-content">
          <p>请确认您已阅读并同意以下内容：</p>
          <ul>
            <li>我已仔细阅读设备使用说明</li>
            <li>我了解设备使用规则和注意事项</li>
            <li>我承诺正确使用设备并按时归还</li>
            <li>我了解如有损坏需要承担相应责任</li>
          </ul>
        </div>
        <div class="dialog-buttons">
          <button class="btn-cancel" @click="showConfirmDialog = false">取消</button>
          <button class="btn-confirm" @click="confirmBooking">确认预约</button>
        </div>
      </div>
    </div>

    <!-- 用户评价组件 -->
    <div class="section">
      <h3>用户评价</h3>
      <device-feedback v-if="deviceInfo.id" :device-id="deviceInfo.id" />
    </div>

    <div class="section">
      <h3>设备预约日历</h3>
      <div class="calendar-container">
        <CalendarView
          :show-date="showDate"
          :items="calendarItems"
          :starting-day-of-week="1"
          class="theme-default holiday-us-traditional holiday-us-official"
        >
          <template #header="{ headerProps }">
            <CalendarViewHeader
              :header-props="headerProps"
              @input="setShowDate"
            />
          </template>
          <template #item="{ item }">
            <div v-if="item" class="calendar-item" :class="item.classes">
              <div class="item-title">{{ item.title || '未知预约' }}</div>
              <div class="item-purpose">使用目的: {{ item.purpose || '未填写' }}</div>
            </div>
          </template>
        </CalendarView>
      </div>
    </div>
  </div>
</template>

<style scoped>
.device-detail {
  max-width: 80%;
  margin: 20px auto;
  padding: 0 20px;
  font-family: sans-serif;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #eee;
}

.header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.header-buttons .button {
  margin-left: 10px;
  padding: 8px 15px;
  text-decoration: none;
  border-radius: 4px;
  transition: background-color 0.3s ease;
  font-size: 14px;
}

.header-buttons .button.primary {
  background-color: #007bff;
  color: white;
  border: 1px solid #007bff;
}

.header-buttons .button:not(.primary) {
    background-color: #f8f9fa;
    color: #333;
    border: 1px solid #ccc;
}

.header-buttons .button:hover {
  opacity: 0.9;
}

.section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.section:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.section h3 {
  font-size: 18px;
  margin-top: 0;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px dashed #ccc;
  color: #555;
}

.instrument-info-block {
  display: flex;
  gap: 20px;
}

.instrument-info-block img {
  width: 200px;
  height: auto;
  object-fit: cover;
  border: 1px solid #ddd;
  padding: 5px;
  background-color: white;
}

.info-list {
  flex-grow: 1;
}

.info-list dl {
  display: flex;
  margin: 8px 0;
  line-height: 1.5;
}

.info-list dt {
  font-weight: bold;
  width: 100px;
  color: #333;
  flex-shrink: 0;
}

.info-list dd {
  margin-left: 10px;
  flex-grow: 1;
  color: #666;
}

.usage-guide {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-top: 10px;
}

.guide-content h4 {
  color: #2c3e50;
  margin: 15px 0 10px;
  font-size: 16px;
}

.notice-list {
  background: #fff;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.notice-list p {
  margin: 8px 0;
  color: #666;
  line-height: 1.6;
}

.manual-content {
  background: #fff;
  padding: 15px;
  border-radius: 6px;
  line-height: 1.6;
}

.usage-records {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-top: 10px;
}

.record-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.record-item {
  background: white;
  padding: 15px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.record-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.user-name {
  font-weight: 500;
  color: #2c3e50;
}

.record-time {
  color: #666;
  font-size: 0.9em;
}

.record-content {
  color: #666;
  line-height: 1.5;
}

.booking-confirm-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
}

.dialog-content h3 {
  margin: 0 0 20px;
  color: #2c3e50;
  text-align: center;
}

.confirm-content {
  margin-bottom: 20px;
}

.confirm-content p {
  margin-bottom: 10px;
  color: #666;
}

.confirm-content ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.confirm-content li {
  padding: 8px 0;
  color: #666;
  display: flex;
  align-items: center;
}

.confirm-content li:before {
  content: "•";
  color: #3498db;
  font-weight: bold;
  margin-right: 8px;
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.dialog-buttons button {
  padding: 8px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-cancel {
  background: #f8f9fa;
  color: #666;
}

.btn-confirm {
  background: #3498db;
  color: white;
}

.btn-cancel:hover {
  background: #e9ecef;
}

.btn-confirm:hover {
  background: #2980b9;
}

.device-comments {
  margin-top: 20px;
}

.no-comments {
  text-align: center;
  color: #666;
  padding: 20px;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.comment-item {
  background: white;
  padding: 15px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.rating-stars {
  display: flex;
  gap: 2px;
}

.star {
  color: #ddd;
  font-size: 16px;
}

.star.active {
  color: #ffd700;
}

.time {
  margin-left: auto;
  color: #666;
  font-size: 0.9em;
}

.comment-content {
  color: #666;
  line-height: 1.5;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.like-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 5px 10px;
  border: 1px solid #ddd;
  border-radius: 15px;
  background: none;
  cursor: pointer;
  transition: all 0.3s;
}

.like-btn:hover {
  background: #f0f0f0;
}

.like-btn.liked {
  color: #1890ff;
  border-color: #1890ff;
}

.like-icon {
  width: 20px;
  height: 20px;
  transition: transform 0.2s;
}

.like-btn:hover .like-icon {
  transform: scale(1.1);
}

.like-btn span {
  font-size: 14px;
  margin-left: 2px;
}

.calendar-container {
  max-width: 100%;
  height: 600px;
  margin-top: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.calendar-item {
  padding: 4px;
  font-size: 12px;
  border-radius: 4px;
  margin: 2px;
}

.item-title {
  font-weight: bold;
  margin-bottom: 2px;
}

.item-purpose {
  font-size: 11px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 预约状态样式 */
.calendar-item.status-pending {
  background-color: #ffda6a;
  border: 1px solid #ffc107;
}

.calendar-item.status-approved {
  background-color: #d4edda;
  border: 1px solid #28a745;
}

.calendar-item.status-rejected {
  background-color: #f8d7da;
  border: 1px solid #dc3545;
}

.calendar-item.status-completed {
  background-color: #e2e3e5;
  border: 1px solid #6c757d;
}

.calendar-item.status-cancelled {
  background-color: #f8f9fa;
  border: 1px solid #adb5bd;
  text-decoration: line-through;
}
</style>
